import data from "@/common/data"
import axios from "axios"
const baseUrl = 'http://82.157.204.174:3000/'
export default ({
  namespaced:true,
  state: {
    Audio:null,//播放器
    timer:null,//计时器
    Player:{
        isPlay:0,//是否播放
        order: 1,//0随机,1表单循环,2单首循环    
    },
    PlayNow: JSON.parse(localStorage.getItem('PlayNow')) || null, //正在播放的歌曲信息
    Songs: JSON.parse(localStorage.getItem('Songs')) || [],//歌曲列表
    ListState:0, //列表状态
    MusicState:0, // 0:关闭 1:最小化 2:正常
    
    keyword:'',
    HotSearch:[],//热搜
    SearchTips:[],//搜索提示
    SearchResult:[],//搜索结果
    ContentState:0, // 0||1:热搜 2:加载 3:搜索提示 4:搜索结果正常 5:搜索结果无 6:搜索结果异常 7:播放歌曲界面

    
  },
  getters: {},
  mutations: {
    //设置音乐播放器状态
    SETSTATE:(state,index)=>state.MusicState =index,
    //设置内容状态
    SETCONTENTSTATE:(state,index) =>{
        if(index > 1 && state.index == 1)
        return
        state.ContentState=index
    },
    //设置热搜
    SETHOTSEARCH:(state,data)=>state.HotSearch=data,
    //设置搜索提示
    SETSEARCHTIPS:(state,data) => state.SearchTips = data,
    //设置搜索结果
    SETSEARCHRESULT:(state,data)=>{
      state.SearchResult=[]
        data.forEach(item => {
            let singer=''
            item.ar.forEach((value,index)=>{	//歌手名字
             if(index>0) singer+='/'+value.name
             else 	 singer+=value.name
            })			 
           let song={
              name:item.name, //歌曲名字
              album:item.al.name,//专辑
              id:item.id,//ID
              singer //歌手
           }
           state.SearchResult.push(song)
        });
    },
    //设置搜索内容
    SETKEYWORD:(state,data) => state.keyword = data,
    //设置歌曲列表状态
    SETLIST:(state,index)=>{
      state.ListState=index
    },
    //加入播放列表
    ADDSONG:(state,data) => {
      state.Songs.push(Object.assign({},data))
      localStorage.setItem('Songs',JSON.stringify(state.Songs))
    },
    //删除某一首
    DELETESONG:(state,id)=>{
       let index = state.Songs.findIndex(item => item.id == id)
       state.Songs.splice(index,1)
       localStorage.setItem('Songs',JSON.stringify(state.Songs))
       if(state.Songs.length == 0)
       localStorage.removeItem('Songs')
    },
    //删除全部
    DELETEALL:(state)=>{
       state.Songs=[]
       localStorage.removeItem('Songs')
       state.PlayNow = null
       localStorage.removeItem('PlayNow')
       state.Player.isPlay=0
       state.Audio.pause()
       clearInterval(state.timer)
       state.ContentState=0
    },

    //初始化
    INIT:(state)=>{
      
        state.Audio=new Audio()
       
       if(state.PlayNow){
          state.Audio.src = state.PlayNow.url 
          state.Audio.currentTime = parseInt(state.PlayNow.star/1000)
       }
    },

    //准备播放
    INITPLAY(state,data){
         if(data ==null){
            state.PlayNow =null
            localStorage.removeItem('PlayNow')
            state.ContentState=0
            return
         }

          if(state.Audio == null){
              state.Audio=new Audio()
          }   
        
          clearInterval(state.timer)
          state.PlayNow = Object.assign({},data)
          localStorage.setItem('PlayNow',JSON.stringify(state.PlayNow))
          state.Audio.src =  state.PlayNow.url  

  
    },
    //暂停播放
    PAUSE(state){
      state.Player.isPlay=0
      state.Audio.pause()
      clearInterval(state.timer)
    },
    //继续播放
    CONTINUE(state){
       state.Player.isPlay=1  
       state.Audio.play()
       state.timer = setInterval(() => {
        state.PlayNow.star += 1000
      }, 1000);
 
    },
    //指定时间播放
    CHANGEPROFRESS:(state,time) =>{
       state.Audio.currentTime =time
       state.PlayNow.star = time*1000
    },
 
  },
  actions:{
    //获取热搜
    async getHotSearch(context){
       try{
         let res =  await axios.get(`/music/search/hot/detail`)
         if(res.data.code ==200) context.commit('SETHOTSEARCH',res.data.data)
         return {code:res.data.code,message:res.data.message}
        }catch(error) {return{code:500,message:error}}
    },
    //获取搜索提示
    async getSearchTips(context,value){
        context.commit('SETCONTENTSTATE',2)
        try{
            let res = await axios({method: 'GET', url: `/music/search/suggest?keywords=${value}&type=mobile`,})
            // let res = await axios.get(`/music/cloudsearch/?keywords=${value}`)
            if(res.data.code ==200)  {
                if(res.data.result.allMatch){
                  context.commit('SETSEARCHTIPS',res.data.result.allMatch)
                  context.commit('SETCONTENTSTATE',3)
                }else    context.commit('SETCONTENTSTATE',5) //空数据
            } else  context.commit('SETCONTENTSTATE',6)      
         
         return {code:res.data.code,message:res.data.message}
        }catch(error) {
                    context.commit('SETCONTENTSTATE',6) 
                     return{code:500,message:error}
                }

    },
     //获取搜索结果
     async getSearchResult(context,value){
        context.commit('SETCONTENTSTATE',2)
        context.commit('SETKEYWORD',value)
        try{
            let res = await axios.get(`/music/cloudsearch/?keywords=${value}`)
            if(res.data.code ==200)  {
                context.commit('SETSEARCHRESULT',res.data.result.songs)
                if(res.data.result.songs.length>0)
                context.commit('SETCONTENTSTATE',4)
                else  context.commit('SETCONTENTSTATE',5)  //空数据
            } else  context.commit('SETCONTENTSTATE',6)        
         
         return {code:res.data.code,message:res.data.message}
        }catch(error) { 
                      context.commit('SETCONTENTSTATE',6) 
                     return{code:500,message:error}
         }

    },
    //获取歌曲详细信息 
    async getSongDetail(context,item){
    
      if(context.state.Songs.find(song => song.id == item.id))
      return context.dispatch('JudgeMusic',context.state.Songs.find(song => song.id == item.id))
   
      context.commit('SETCONTENTSTATE',2)
      try{
        let res = await axios.get(`/music/song/detail?ids=${item.id}`)
        if(res.data.code==200)
        {
          let music=item //包含id,歌手名字,歌曲名字
          music.songlength=res.data.songs[0].dt //时长
          music.star=0   //开始
          music.end=res.data.songs[0].dt //结束
          music.picurl=res.data.songs[0].al.picUrl //歌曲图片	

          context.dispatch('playSong',music)
        }  else context.commit('SETCONTENTSTATE',6) 
      }catch(error) {  context.commit('SETCONTENTSTATE',6) 
                        return{code:500,message:error}}
    },
    //获取歌曲播放链接并播发歌曲
    async playSong(context,item){
      try{
        let res = await axios.get(`/music/song/url?id=${item.id}`)
        if(res.data.code==200)
        {
          let music=item //包含id,歌手名字,歌曲名字,时长,歌曲图片
		 			music.url=res.data.data[0].url
          context.commit('ADDSONG',music)
          context.dispatch('JudgeMusic',music)
          context.commit('SETCONTENTSTATE',7)
        }  else context.commit('SETCONTENTSTATE',6) 
      }catch(error) {  context.commit('SETCONTENTSTATE',6) 
                        return{code:500,message:error}}
    },
    //初始化
    init(context){
      context.commit('INIT')
      // context.state.Audio.addEventListener('ended',context.dispatch('ended'));

      context.state.Audio.addEventListener('ended', () => {
        context.commit('PAUSE')
        context.dispatch('findIndex',2)
        context.commit('CONTINUE')
     });
   

    },
    //判断播放
    JudgeMusic(context,music){
      

      if(context.state.PlayNow)
      context.commit('SETCONTENTSTATE',7)
      if(context.state.PlayNow && context.state.PlayNow.id == music.id){ 
          context.commit('CONTINUE')
      }else  {
        context.commit('INITPLAY',music)
        context.commit('CONTINUE')
      }

      

      
    },
    //通过ID播放歌曲
    PlayById(context,id){
       let index = context.state.Songs.findIndex( item => item.id == id)
       let music = context.state.Songs[index]
       context.dispatch('JudgeMusic',music)
    },
    //播放下一曲 上一曲
    findIndex(context,type){
      let index = context.state.Songs.findIndex( item => item.id == context.state.PlayNow.id)
      if(index == -1) return context.commit('REFRESH') //歌曲删完了
      let max =context.state.Songs.length-1
      if(type == 1){ //上一曲
         index -=1
      }else if(type == 2){//下一曲
         index +=1
      }
      if(index <0) index =max
      if(index >max) index =0
      let id = context.state.Songs.findIndex( item => item.id == context.state.PlayNow.id).id
      let music = context.state.Songs[index]
      context.commit('INITPLAY',music)
    },
    //删除歌曲
    deleteSong(context,id){
      if(id == context.state.PlayNow.id)//删除正在播放的歌曲了
      {
        context.dispatch('findIndex',2)
        if(context.state.Player.isPlay==0)
          context.commit('PAUSE')
      }   
      context.commit('DELETESONG',id)
      if(id == context.state.PlayNow.id)
      {
        context.commit('PAUSE')
        context.commit('INITPLAY',null) //歌曲删完了
      }else context.commit('CONTINUE')
    }
    ////
  },
})